package com.wu.shiro;

import com.wu.entity.ShiroUser;
import com.wu.service.RoleService;
import com.wu.service.impl.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShiroDbRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * shiro认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String loginName = token.getUsername();
        if (loginName != null && !"".equals(loginName)) {
            // 通過登录名获取用户
            ShiroUser user = userService.getUserByLoginName(loginName);
            if (user != null) {
                // 如果身份认证验证成功，返回一个AuthenticationInfo实现
                return new SimpleAuthenticationInfo(user.getLoginName(),
                        user.getPassword(), getName());
            }
        }
        return null;
    }

    /**
     * shiro授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String loginName = (String) getAvailablePrincipal(principals); // 使用Shiro提供的方法获取用户名称
        if (loginName != null) {
            String roleId = userService.getRoleIdByLoginName(loginName);

            // 获取用户的权限
            List<String> permTokens = roleService.getPermTokens(roleId);

            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if (roleId != null) {
                info.addRole(roleId); // 加入用户角色
            }
            if (permTokens != null) {
                info.addStringPermissions(permTokens); // 加入用户许可标记
            }
            return info;
        }
        return null;
    }
}
